﻿using EFFC.Frame.Net.Module.Extend.EWRA.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFFC.Extends.LinqDLR2SQL;
using EFFC.Frame.Net.Unit.DB;
using EFFC.Frame.Net.Base.Data.Base;
using EFFC.Frame.Net.Module.Extend.EWRA.Attributes.Validation;
using EFFC.Frame.Net.Base.Common;
using EFFC.Frame.Net.Base.Data;
using EFFC.Frame.Net.Module.Business.Datas;
using ICPFrameLib.Business;
using ICPFrameLib.Attributes;
using EFFC.Frame.Net.Unit.DB.Parameters;

namespace XHRPMIS.Business.v1._0
{
    public class DynamicComponet : MyRestLogic
    {

        [EWRARoute("get", "/d_component")]
        [EWRARouteDesc("获取动态组件列表")]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息',
data:[{
    uid:'UID',
    name:'动态组件名称',
    route:'动态组件路由',
    category:'分类',
    is_lock:'是否锁定',
    is_error:'是否出错',
    error_msg:'错误信息描述',
    is_warnning:'是否警告',
    warnning_msg:'警告信息'
}]
}")]
        object Select()
        {
            SetCacheEnable(false);
            var up = DB.NewMetaUnitParameter();

            var list = (from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                        select new
                        {
                            uid = t.UID,
                            name = t.Name,
                            route = t.Route,
                            category = t.Category,
                            is_lock = t.IsLock,
                            is_error = t.IsError,
                            error_msg = t.ErrorMsg,
                            is_warnning = t.IsWarnning,
                            warnning_msg = t.WarnningMsg
                        }).GetQueryList(up);
            foreach (dynamic item in list)
            {
                item.is_lock = BoolStd.IsNotBoolThen(item.is_lock);
                item.is_error = BoolStd.IsNotBoolThen(item.is_error);
                item.is_warnning = BoolStd.IsNotBoolThen(item.is_warnning);
            }

            return new
            {
                code = "success",
                msg = "",
                data = list
            };
        }
        [EWRARoute("get", "/d_component/{uid}")]
        [EWRARouteDesc("获取指定的动态组件")]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息',
data:{
    uid:'UID',
    name:'动态组件名称',
    desc:'动态组件描述'，
    route:'动态组件路由',
    category:'分类',
    is_lock:'是否锁定'，
    settings:'动态组件的相关设定，JSON格式',
    is_error:'是否出错',
    error_msg:'错误信息描述',
    is_warnning:'是否警告',
    warnning_msg:'警告信息'
}
}")]
        object Select(string uid)
        {
            SetCacheEnable(false);
            var up = DB.NewMetaUnitParameter();

            var list = (from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                        where t.UID == uid
                        select new
                        {
                            uid = t.UID,
                            name = t.Name,
                            desc = t.Desc,
                            category = t.Category,
                            route = t.Route,
                            is_lock = t.IsLock,
                            settings = t.SettingsJson,
                            is_error = t.IsError,
                            error_msg = t.ErrorMsg,
                            is_warnning = t.IsWarnning,
                            warnning_msg = t.WarnningMsg
                        }).GetQueryList(up);
            if (list.Count <= 0)
            {
                return new
                {
                    code = "failed",
                    msg = "指定的组件不存在"
                };
            }
            dynamic info = list.First();

            info.is_lock = BoolStd.IsNotBoolThen(info.is_lock);
            info.is_error = BoolStd.IsNotBoolThen(info.is_error);
            info.is_warnning = BoolStd.IsNotBoolThen(info.is_warnning);

            return new
            {
                code = "success",
                msg = "",
                data = info
            };
        }
        [EWRARoute("post", "/d_component")]
        [EWRARouteDesc("新增一个动态组件")]
        [EWRAEmptyValid("name,route")]
        [EWRAAddInput("name", "string", "名称", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAAddInput("desc", "string", "描述", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("category", "string", "分类", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("settings", "string", "设定参数，JSON格式的字符串", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("route", "string", "路由", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息',
uid:'新增成功后返回的UID'
}")]
        object Add()
        {
            var up = DB.NewMetaUnitParameter();
            var name = ComFunc.nvl(PostDataD.name);
            var desc = ComFunc.nvl(PostDataD.desc);
            var settings = ComFunc.nvl(PostDataD.settings);
            var route = ComFunc.nvl(PostDataD.route);
            var category = ComFunc.nvl(PostDataD.category);

            if ((from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                 where t.Name == name
                 select t).IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "同名组件已经存在"
                };
            }
            var uid = Guid.NewGuid().ToString();
            DB.QuickInsert(up, "EXTEND_DYNAMIC_COMPONENT", new
            {
                UID = uid,
                Name = name,
                Desc = desc,
                Category = category,
                Route = route,
                IsLock = 0,
                SettingsJson = settings,
                IsError = 0,
                IsWarnning = 0,
                add_id = TokenPayLoad.ID,
                add_ip = ClientInfo.IP,
                add_name = ComFunc.nvl(TokenPayLoad["username"]),
                add_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                last_id = TokenPayLoad.ID,
                last_ip = ClientInfo.IP,
                last_name = ComFunc.nvl(TokenPayLoad["username"]),
                last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            });

            return new
            {
                code = "success",
                msg = "操作成功",
                uid
            };
        }
        [EWRARoute("patch", "/d_component/{uid}")]
        [EWRARouteDesc("修改一个动态组件")]
        [EWRAEmptyValid("name,route")]
        [EWRAAddInput("uid", "string", "uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAAddInput("name", "string", "名称", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAAddInput("desc", "string", "描述", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("category", "string", "分类", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("settings", "string", "设定参数，JSON格式的字符串", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, true)]
        [EWRAAddInput("route", "string", "路由", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息',
uid:'成功后返回的UID'
}")]
        object Modify(string uid)
        {
            var up = DB.NewMetaUnitParameter();
            var name = ComFunc.nvl(PostDataD.name);
            var desc = ComFunc.nvl(PostDataD.desc);
            var settings = ComFunc.nvl(PostDataD.settings);
            var route = ComFunc.nvl(PostDataD.route);
            var category = ComFunc.nvl(PostDataD.category);

            var s = from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                    where t.UID == uid
                    select t;


            if (!s.IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "组件不存在"
                };
            }
            dynamic info = s.GetQueryList(up).First();
            if (BoolStd.IsNotBoolThen(info.IsLock))
            {
                return new
                {
                    code = "failed",
                    msg = "组件锁定中，不可删除(删除可能会导致其它组件失效或出现异常，请谨慎操作)"
                };
            }

            if ((from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                 where t.Name == name && t.UID != uid
                 select t).IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "同名组件已经存在"
                };
            }
            DB.QuickUpdate(up, "EXTEND_DYNAMIC_COMPONENT", new
            {
                Name = name,
                Desc = desc,
                Category = category,
                Route = route,
                SettingsJson = settings,
                last_id = TokenPayLoad.ID,
                last_ip = ClientInfo.IP,
                last_name = ComFunc.nvl(TokenPayLoad["username"]),
                last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            }, new
            {
                UID = uid
            });

            return new
            {
                code = "success",
                msg = "操作成功",
                uid
            };
        }
        [EWRARoute("delete", "/d_component/{uid}")]
        [EWRARouteDesc("删除一个动态组件")]
        [EWRAAddInput("uid", "string", "uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息'
}")]
        object Delete(string uid)
        {
            var up = DB.NewMetaUnitParameter();
            var s = from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                    where t.UID == uid
                    select t;
            if (!s.IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "组件不存在"
                };
            }

            dynamic info = s.GetQueryList(up).First();
            if (BoolStd.IsNotBoolThen(info.IsLock))
            {
                return new
                {
                    code = "failed",
                    msg = "组件锁定中，不可删除(删除可能会导致其它组件失效或出现异常，请谨慎操作)"
                };
            }

            DB.QuickDelete(up, "EXTEND_DYNAMIC_COMPONENT", new
            {
                UID = uid
            });

            return new
            {
                code = "success",
                msg = "操作成功"
            };
        }
        [EWRARoute("patch", "/d_component/{uid}/lock")]
        [EWRARouteDesc("锁定一个动态组件")]
        [EWRAAddInput("uid", "string", "uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息'
}")]
        object Active(string uid)
        {
            var up = DB.NewMetaUnitParameter();

            var s = from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                    where t.UID == uid
                    select t;
            if (!s.IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "组件不存在"
                };
            }

            dynamic info = s.GetQueryList(up).First();
            if (BoolStd.IsNotBoolThen(info.IsLock))
            {
                return new
                {
                    code = "failed",
                    msg = "组件未锁定，无需重复操作"
                };
            }
            DB.QuickUpdate(up, "EXTEND_DYNAMIC_COMPONENT", new
            {
                IsLock = 1,
                last_id = TokenPayLoad.ID,
                last_ip = ClientInfo.IP,
                last_name = ComFunc.nvl(TokenPayLoad["username"]),
                last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            }, new
            {
                UID = uid
            });

            return new
            {
                code = "success",
                msg = "操作成功"
            };
        }
        [EWRARoute("patch", "/d_component/{uid}/unlock")]
        [EWRARouteDesc("解锁一个动态组件")]
        [EWRAAddInput("uid", "string", "uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息'
}")]
        object Deactive(string uid)
        {
            var up = DB.NewMetaUnitParameter();

            var s = from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                    where t.UID == uid
                    select t;
            if (!s.IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "组件不存在"
                };
            }

            dynamic info = s.GetQueryList(up).First();
            if (!BoolStd.IsNotBoolThen(info.IsLock))
            {
                return new
                {
                    code = "failed",
                    msg = "组件未锁定活，无需重复操作"
                };
            }
            DB.QuickUpdate(up, "EXTEND_DYNAMIC_COMPONENT", new
            {
                IsLock = 0,
                last_id = TokenPayLoad.ID,
                last_ip = ClientInfo.IP,
                last_name = ComFunc.nvl(TokenPayLoad["username"]),
                last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            }, new
            {
                UID = uid
            });

            return new
            {
                code = "success",
                msg = "操作成功"
            };
        }
        [EWRARoute("patch", "/d_component/{uid}/correct")]
        [EWRARouteDesc("标记一个动态组件正确")]
        [EWRAAddInput("uid", "string", "uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息'
}")]
        object Correct(string uid)
        {
            var up = DB.NewMetaUnitParameter();
            BeginTrans();
            var msg = "";
            if (!DoCorrect(up, uid, ref msg, TokenPayLoad.ID, ComFunc.nvl(TokenPayLoad["username"]), ClientInfo.IP))
            {
                RollBack();
                return new
                {
                    code = "failed",
                    msg
                };
            }
            CommitTrans();

            return new
            {
                code = "success",
                msg = "操作成功"
            };
        }
        [EWRARoute("patch", "/d_component/{uid}/ignore_warn")]
        [EWRARouteDesc("忽略一个动态组件的警告")]
        [EWRAAddInput("uid", "string", "uid", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:'success-成功，failed-失败',
msg:'提示信息'
}")]
        object IgnoreWarn(string uid)
        {
            var up = DB.NewMetaUnitParameter();
            BeginTrans();
            var msg = "";
            if (!DoIgnorWarn(up, uid, ref msg, TokenPayLoad.ID, ComFunc.nvl(TokenPayLoad["username"]), ClientInfo.IP))
            {
                RollBack();
                return new
                {
                    code = "failed",
                    msg
                };
            }
            CommitTrans();

            return new
            {
                code = "success",
                msg = "操作成功"
            };
        }
        /// <summary>
        /// 标记表单有错
        /// </summary>
        /// <param name="uid">动态表单uid或关联外键资料key</param>
        /// <param name="errormsg">错误原因描述</param>
        /// <returns></returns>
        public bool DoError(UnitParameter up, string id, string errormsg, ref string msg, string login_id = "", string login_name = "", string login_ip = "")
        {
            var list = (from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                        where t.UID == id || t.RefKey == id
                        select t).GetQueryList(up);
            if (list.Count <= 0)
            {
                msg = "指定的组件不存在";
                return false;
            }
            foreach (dynamic info in list)
            {
                DB.QuickUpdate(up, "EXTEND_DYNAMIC_COMPONENT", new
                {
                    IsError = 1,
                    ErrorMsg = errormsg,
                    last_id = login_id,
                    last_name = login_name,
                    last_ip = login_ip,
                    last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                }, new
                {
                    info.uid

                });
            }

            return true;
        }
        /// <summary>
        /// 标记表单正确
        /// </summary>
        /// <param name="id"></param>
        /// <param name="errormsg"></param>
        /// <param name="msg"></param>
        /// <param name="login_id"></param>
        /// <param name="login_name"></param>
        /// <param name="login_ip"></param>
        /// <returns></returns>
        public bool DoCorrect(UnitParameter up, string id, ref string msg, string login_id = "", string login_name = "", string login_ip = "")
        {
            var list = (from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                        where t.UID == id || t.RefKey == id
                        select t).GetQueryList(up);
            if (list.Count <= 0)
            {
                msg = "指定的组件不存在";
                return false;
            }
            foreach (dynamic info in list)
            {
                DB.QuickUpdate(up, "EXTEND_DYNAMIC_COMPONENT", new
                {
                    IsError = 0,
                    ErrorMsg = "",
                    last_id = login_id,
                    last_name = login_name,
                    last_ip = login_ip,
                    last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                }, new
                {
                    info.uid

                });
            }
            return true;
        }
        /// <summary>
        /// 标记表单警告
        /// </summary>
        /// <param name="uid">动态表单uid或关联外键资料key</param>
        /// <param name="warnmsg">警告信息描述</param>
        /// <returns></returns>
        public bool DoWarn(UnitParameter up, string id, string warnmsg, ref string msg, string login_id = "", string login_name = "", string login_ip = "")
        {
            var list = (from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                        where t.UID == id || t.RefKey == id
                        select t).GetQueryList(up);
            if (list.Count <= 0)
            {
                msg = "指定的组件不存在";
                return false;
            }
            foreach (dynamic info in list)
            {
                DB.QuickUpdate(up, "EXTEND_DYNAMIC_COMPONENT", new
                {
                    IsWarnning = 1,
                    WarnningMsg = warnmsg,
                    last_id = login_id,
                    last_name = login_name,
                    last_ip = login_ip,
                    last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                }, new
                {
                    info.uid

                });
            }

            return true;
        }
        /// <summary>
        /// 标记表单正确
        /// </summary>
        /// <param name="id"></param>
        /// <param name="errormsg"></param>
        /// <param name="msg"></param>
        /// <param name="login_id"></param>
        /// <param name="login_name"></param>
        /// <param name="login_ip"></param>
        /// <returns></returns>
        public bool DoIgnorWarn(UnitParameter up, string id, ref string msg, string login_id = "", string login_name = "", string login_ip = "")
        {
            var list = (from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                        where t.UID == id || t.RefKey == id
                        select t).GetQueryList(up);
            if (list.Count <= 0)
            {
                msg = "指定的组件不存在";
                return false;
            }
            foreach (dynamic info in list)
            {
                DB.QuickUpdate(up, "EXTEND_DYNAMIC_COMPONENT", new
                {
                    IsWarnning = 0,
                    WarnningMsg = "",
                    last_id = login_id,
                    last_name = login_name,
                    last_ip = login_ip,
                    last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                }, new
                {
                    info.uid

                });

            }
            return true;
        }
        /// <summary>
        /// 表单绑定外键资料
        /// </summary>
        /// <param name="up"></param>
        /// <param name="uid"></param>
        /// <param name="refkey"></param>
        /// <param name="msg"></param>
        /// <param name="login_id"></param>
        /// <param name="login_name"></param>
        /// <param name="login_ip"></param>
        /// <returns></returns>
        public bool DoBindRefKey(UnitParameter up, string uid, string refkey, ref string msg, string login_id = "", string login_name = "", string login_ip = "")
        {
            var list = (from t in DB.LamdaTable(up, "EXTEND_DYNAMIC_COMPONENT", "a")
                        where t.UID == uid
                        select t).GetQueryList(up);
            if (list.Count <= 0)
            {
                msg = "指定的组件不存在";
                return false;
            }
            dynamic info = list.First();
            DB.QuickUpdate(up, "EXTEND_DYNAMIC_COMPONENT", new
            {
                RefKey = refkey,
                last_id = login_id,
                last_name = login_name,
                last_ip = login_ip,
                last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            }, new
            {
                info.uid

            });

            return true;
        }
    }
}
